#!/usr/bin/env bash
#
# bazel-clippy without all the noise


set -o xtrace
set -o errexit
set -o nounset
set -o pipefail

# Run bazel clippy.
#
# The clippy results are captured in an output file, so we can neatly summarize
# them after all of the build noise.
bazel_args=(
    # Get as many errors as we can in the output
    --keep_going
    # Use the cache
    --config=unsafe-fast-presubmit
    # Do clippy stuff
    --config=clippy
)

bazel_args_for_capture=(
    # Get as many errors as we can in the output
    --keep_going
    # Use the cache
    --config=unsafe-fast-presubmit
    # Do clippy stuff
    --config=clippy
    # Results are captured in bazel-bin/<package>/<target_name>.clippy.out
    --@rules_rust//rust/settings:capture_clippy_output=True
)


# Run it on everything except for all third_party targets
bazel_targets=("//...")
bazel_exclude_targets=("-third_party/...")

set +o errexit # Don't fail yet for this one.
# First we run it once, get the full output, and capture the actual result code.
bazel build "${bazel_args[@]}" -- "${bazel_targets[@]}" "${bazel_exclude_targets[@]}"
readonly actual_result=$?
set -o errexit

# Now run the command, capturing only clippy output.
# This command won't fail on clippy issues, but will on build or other issues.
echo "Re-running to capture nice output..."
bazel build "${bazel_args_for_capture[@]}" -- "${bazel_targets[@]}" "${bazel_exclude_targets[@]}"

set +o xtrace # Don't echo this complicated command.
find bazel-bin/* -name "*.clippy.out" -print0 | xargs -0 cat | awk '
BEGIN {
    line_count = 0
    print "   /‾‾\\"
    print "   ▏  ▕"
    print "  (o) (o)"
    print "   ▏▏ ▕ /"
    print "   ▏▏ ▕▕"
    print "   ▏\\_/▕"
    print "   \\___/"
    print "     /\\"
    print "/‾‾‾‾  ‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾\\"
}
{
    line_count++
    if (line_count == 1) {
      print "Hi!"
      print ""
      print "It looks like you''re trying to write idiomatic Rust!"
      print ""
      print "Have you considered making these improvements?"
      print ""
    }
    print $0
}
END {
    if (line_count == 0) {
        print " no errors found, have a wonderful day."
        print "\\________________________________________________________/"
    } else {
        print ""
        print "Hope this helps!"
        print ""
        print "\\________________________________________________________/"
    }
}
'

# Send proper exit code
exit $actual_result
